package com.example.tool.action.sso;

import com.example.tool.action.ActionUtil;
import com.example.tool.ui.HToolIcon;
import com.example.tool.utils.FileUtil;
import com.example.tool.utils.SwingUtil;
import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFileManager;
import org.jetbrains.annotations.NotNull;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

/**
 * <p>Title: AopActions</p>
 * Description: 创建单点登陆到OA
 * <p>CreateTime: 2022/6/27 18:10</p>
 * @author FT
 */
public class SSOInActions extends AnAction {

  @Override
  public @NotNull ActionUpdateThread getActionUpdateThread() {
    return super.getActionUpdateThread();
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    String[] configInformation = ActionUtil.getInformation(e.getProject());
    if (configInformation != null) {
      String file = "/" + configInformation[2] + "/WEB-INF/cfgHome/plugin/" + configInformation[1] + "/spring/spring-" + configInformation[1] + "-sso.xml";
      SwingUtil.setTips("创建该文件时，如果项目中已经存在指定文件将会覆盖它。<br><span style=\"color: #F56C6C; font-size: 8px;\">" + file + "</span>");
      ActionUtil.ActionCreatInput(e, (information, value) -> {
        String className = value.get(0);
        // xx.java
        FileUtil.generateFile(information[0] + "/" + className + ".java", "/demo/init/sso/SingleSignOnLogin.txt",
            str -> str.replace("$package$", information[1])
                .replace("$ClassName$", className)
                .replace("$className$", FileUtil.lowerFirstCase(className))
                .replace("$TIME$", new SimpleDateFormat("yyyy-MM-dd").format(new Date())));

        // spring-XX-sso.xml
        String xmlPath = Objects.requireNonNull(e.getProject()).getBasePath() + "/" + configInformation[2] + "/WEB-INF/cfgHome/plugin/" + configInformation[1] + "/spring";
        String filePath = xmlPath + "/spring-" + configInformation[1] + "-sso.xml";
        FileUtil.generateFile(filePath, "/demo/spring/spring-demo-sso.txt",
            str -> str.replace("$ClassPath$", information[1] + "." + className)
                .replace("$className$", FileUtil.lowerFirstCase(className)));
        VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
      }, "单点登陆类名: ");
      SwingUtil.setTips(null);
    } else {
      Messages.showMessageDialog(
          e.getProject(),
          "The seeyon configuration file is required, but the corresponding file is not found or the file is incorrect, please reset it!",
          "Error",
          HToolIcon.ModuleIcon);
    }
  }

  @Override
  public void update(@NotNull AnActionEvent event) {
    ActionUtil.ActionP(event);
  }
}
